package com.lottery.ruok.lottrey.ui.component;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.ChuantongcaiActivity;
import com.lottery.ruok.lottrey.activity.LiuhecaiDetailActivity;
import com.lottery.ruok.lottrey.activity.LiuhecaiPrizeActivity;
import com.lottery.ruok.lottrey.activity.LoginActivity;
import com.lottery.ruok.lottrey.activity.OfficalLotteryDetailActivity;
import com.lottery.ruok.lottrey.activity.PlayRuleActivity;
import com.lottery.ruok.lottrey.activity.PrizeListActivity;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.AddFavorRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.RemoveFavorRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.AddFavorResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GetWholeCategoryResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.OperationSuccessResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.nex3z.flowlayout.FlowLayout;

import butterknife.BindView;
import butterknife.ButterKnife;
import glideHelp.GlideHelper;
import ui.AreaCircle;
import ui.IToast;
import utils.Utils;

/**
 * 购买彩票ItemView
 */
public class BuyItemView extends BaseRelativeLayout {
    @BindView(R.id.logo)
    ImageView logo;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.number)
    TextView number;
    @BindView(R.id.tip)
    TextView tip;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.play)
    RelativeLayout play;
    @BindView(R.id.choose)
    ImageView choose;
    @BindView(R.id.favor_button)
    TextView favorButton;
    @BindView(R.id.favor)
    LinearLayout favor;
    @BindView(R.id.numberTrend)
    LinearLayout numberTrend;
    @BindView(R.id.play_rule)
    LinearLayout playRule;
    @BindView(R.id.container)
    FlowLayout container;

    private GetWholeCategoryResponse.ItemsBean data;

    public BuyItemView(Context context) {
        super(context);
    }

    public BuyItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public BuyItemView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void init(Context context, AttributeSet attrs, int defStyleAttr) {

    }

    @Override
    protected void initView(Context context) {
        LayoutInflater.from(mContext).inflate(R.layout.buy_category_item, this);
        ButterKnife.bind(this, BuyItemView.this);

    }

    @Override
    protected void load(Context context) {

    }

    public void setData(final GetWholeCategoryResponse.ItemsBean data, GetWholeCategoryResponse.AttachedBean attachedBean) {
        try {
            GlideHelper.loadImage(mContext, data.getImage_url(), logo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.data = data;
        name.setText(data.getName());
        if (data.getPrize_num() != null && data.getPrize_num().contains(",")) {
            String[] temp = data.getPrize_num().split(",");
            number.setVisibility(View.GONE);
            container.setVisibility(View.VISIBLE);
            container.removeAllViews();
            RelativeLayout.LayoutParams tip_layoutParams = (RelativeLayout.LayoutParams) tip.getLayoutParams();
            tip_layoutParams.topMargin = Utils.dip2px(mContext, 3);
            tip.setLayoutParams(tip_layoutParams);

            if (data.getCode().equals("xglhc") || data.getCode().equals("jslhc")|| data.getCode().equals("js10flhc")) {
                if (attachedBean != null) {
                    if (temp.length == attachedBean.getColor().size()) {
                        for (int t = 0; t < temp.length; t++) {
                            TextView areaCircle = new TextView(mContext);
                            switch (attachedBean.getColor().get(t)) {
                                case "red":
//                                areaCircle.setBackground(Color.parseColor("#df5f5f"));
                                    areaCircle.setBackgroundResource(R.mipmap.red_big);
                                    break;
                                case "green":
//                                areaCircle.setBackground(Color.parseColor("#85ba75"));
                                    areaCircle.setBackgroundResource(R.mipmap.green_big);
                                    break;
                                default:
//                                areaCircle.setBackground(Color.parseColor("#7b95e0"));
                                    areaCircle.setBackgroundResource(R.mipmap.blue_big);
                                    break;
                            }
                            areaCircle.setText(temp[t]);
                            areaCircle.setGravity(Gravity.CENTER);
                            areaCircle.setTextColor(Color.parseColor("#3f3f3f"));
                            areaCircle.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                            layoutParams.rightMargin = Utils.dip2px(mContext, 6);
                            areaCircle.setLayoutParams(layoutParams);
                            container.addView(areaCircle);
                        }
                    }
                }
            } else if("ahk3".equals(data.getCode())||"jiangsuk3".equals(data.getCode())||Common.isK3(data.getCode())){
                // 快3的图片显示
                for (String s : temp) {
                    int num = Integer.parseInt(s);
                    ImageView imageView = new ImageView(mContext);
                    imageView.setImageResource(Common.getDiceDrawable(num));
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(mContext, 20), Utils.dip2px(mContext, 20));
                    layoutParams.rightMargin = Utils.dip2px(mContext, 6);
                    imageView.setLayoutParams(layoutParams);
                    container.addView(imageView);
                }
            } else {
                for (String s : temp) {
                    AreaCircle areaCircle = new AreaCircle(mContext);
                    Common.setBallBackground(areaCircle, s, data.getCode());
                    areaCircle.setText(s);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(Utils.dip2px(mContext, 20), Utils.dip2px(mContext, 20));
                    layoutParams.rightMargin = Utils.dip2px(mContext, 6);
                    areaCircle.setLayoutParams(layoutParams);
                    container.addView(areaCircle);
                }
            }
        } else {
            number.setText(data.getPrize_num());
            number.setVisibility(View.VISIBLE);
            container.setVisibility(View.GONE);
            RelativeLayout.LayoutParams tip_layoutParams = (RelativeLayout.LayoutParams) tip.getLayoutParams();
            tip_layoutParams.topMargin = Utils.dip2px(mContext, 20);
            tip.setLayoutParams(tip_layoutParams);
        }

        tip.setText("距离第" + data.getNo() + "截止还有");

        time.setText(Utils.getCountTimeByLong((data.getTime() - data.pasttime) * 1000));
        time.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            @Override
            public void afterTextChanged(Editable editable) {
                if (editable.toString().equals("00:00:00")) {
                    data.setTime(data.getInterval());
                    data.pasttime = 0;
                }
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                categoryFragment.//sendAnalyticMsg("lottery_" + categoryFragment.ANALYTIC_VERSION + "_" + data.getCode() + "_buylottery_jump");

                gotoLotteryDetailActivity(data.getCode(), data.getItem_class());
            }
        });

        numberTrend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                categoryFragment.//sendAnalyticMsg("lottery_" + categoryFragment.ANALYTIC_VERSION + "_" + data.getCode() + "_buylottery_num_trend");

                if (data.getCode().equals("xglhc") || data.getCode().equals("jslhc")|| data.getCode().equals("js10flhc")) {
                    Intent intent = new Intent(mContext, LiuhecaiPrizeActivity.class);
                    intent.putExtra("code", data.getCode());
                    mContext.startActivity(intent);
                } else {
                    Intent intent = new Intent(mContext, PrizeListActivity.class);
                    intent.putExtra("code", data.getCode());
                    mContext.startActivity(intent);
                }
            }
        });
        playRule.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                categoryFragment.//sendAnalyticMsg("lottery_" + categoryFragment.ANALYTIC_VERSION + "_" + data.getCode() + "_buylottery_rule");

                Intent intent = new Intent(mContext, PlayRuleActivity.class);
                intent.putExtra("code", data.getCode());
                mContext.startActivity(intent);
            }
        });

        favor.setOnClickListener(null);
        favor.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (UserInfo.getToken().equals("")) {
                    gotoLoginActivity();
                } else {
                    if (data.getIs_favorite() == 1) {
                        //取消收藏
                        RetrofitBase.getRetrofit().create(RemoveFavorRequest.class).getResult(UserInfo.getToken(), data.getCode())
                                .compose(RxHelper.<OperationSuccessResponse>handleResult())
                                .subscribe(new RxSubscribe<OperationSuccessResponse>(mContext) {
                                    @Override
                                    protected void _onNext(OperationSuccessResponse operationSuccessResponse) {
                                        Utils.showToast("取消收藏");

                                        data.setIs_favorite(0);

                                        updateFavorite(data);
                                    }

                                    @Override
                                    protected boolean showDialog() {
                                        return true;
                                    }
                                });

//                        categoryFragment.//sendAnalyticMsg("lottery_" + categoryFragment.ANALYTIC_VERSION + "_" + data.getCode() + "_buylottery_cancelcollection");
                    } else {
                        //加入收藏
                        RetrofitBase.getRetrofit().create(AddFavorRequest.class).getResult(UserInfo.getToken(), data.getCode())
                                .compose(RxHelper.<AddFavorResponse>handleResult())
                                .subscribe(new RxSubscribe<AddFavorResponse>(mContext) {
                                    @Override
                                    protected void _onNext(AddFavorResponse addFavorResponse) {
                                        IToast.show("收藏成功！", mContext);

                                        data.setIs_favorite(1);

                                        updateFavorite(data);
                                    }

                                    @Override
                                    public boolean showDialog() {
                                        return true;
                                    }
                                });

//                        categoryFragment.//sendAnalyticMsg("lottery_" + categoryFragment.ANALYTIC_VERSION + "_" + data.getCode() + "_buylottery_collection");
                    }
                }
            }
        });
        updateFavorite(data);


    }

    private void updateFavorite(GetWholeCategoryResponse.ItemsBean data) {
        if (data.getIs_favorite() == 1) {
            favorButton.setTextColor(Color.parseColor("#f45300"));
            choose.setImageResource(R.mipmap.liked);
        } else {
            favorButton.setTextColor(Color.parseColor("#ffac82"));
            choose.setImageResource(R.mipmap.like);
        }
    }

    public void gotoLoginActivity() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(intent);
        ((Activity) mContext).overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
    }


    public void gotoLotteryDetailActivity(String code, int index) {//0 其它 1官方2六合3传统
        switch (index) {
            case 1: {
                Intent intent = new Intent(mContext, OfficalLotteryDetailActivity.class);
                intent.putExtra("code", code);
                mContext.startActivity(intent);
                break;
            }
            case 2: {
                Intent intent = new Intent(mContext, LiuhecaiDetailActivity.class);
                intent.putExtra("code", code);
                mContext.startActivity(intent);
                break;
            }
            case 3: {
                Intent intent = new Intent(mContext, ChuantongcaiActivity.class);
                intent.putExtra("code", code);
                mContext.startActivity(intent);
                break;
            }
        }
    }

    public void refreshTime() {
        if (null == data || data.getTime() <= 0) return;
        time.setText(Utils.getCountTimeByLong((data.getTime() - data.pasttime) * 1000));
    }
}
